
static char RCSId[]="$Id: DoubleValueSortedList.m,v 1.1.1.1 1993/03/18 03:31:39 davis Exp $";


#import "DoubleValueSortedList.h"
#import "TicObject.h"

@implementation DoubleValueSortedList


- init
{
    [super init];
    isAscending = YES;

    return self;
}


- setAscending:(BOOL)aBool
{
    isAscending = aBool;
    [self _reorderObjects];
    return self;
}


- (BOOL) isAscending
{
    return isAscending;
}


- addObject:anObject
{
    if (anObject) {
	double value;
	int count;

	/*  
	 *  Get the sort value of the object and insert it at the 
	 *  correct place in the list.
	 */

	value = [anObject doubleValue];
	for (count = 0 ; count < numElements ; count++) {
	    switch (isAscending) {
	    case YES:
		if ([[self objectAt:count] doubleValue] > value)
		    return [super insertObject:anObject at:count];
		break;
	    case NO:
		if ([[self objectAt:count] doubleValue] < value)
		    return [super insertObject:anObject at:count];
		break;
	    }
	}

	return [super insertObject:anObject at:numElements];
    }

    return nil;
}



/** Overridden to do nothing **/

- insertObject:anObject at:(unsigned)index
{
    return nil;
}


- replaceObjectAt:(unsigned) index with:newObject
{
    return nil;
}



/** Private methods **/

- _reorderObjects
{
    int count;
    BOOL done = NO;

    if (!numElements || (numElements == 1))
	return self;


    /*  Do a simple bubble sort (the list is assumed to be fairly small). */

    while (!done) {
	done = YES;
	for (count = 0 ; count < (numElements - 1) ; count++) {
	    switch (isAscending) {
	    case YES:
		if ([[self objectAt:count] doubleValue] > 
		    [[self objectAt:count + 1] doubleValue]) {    /* Swap */
		    [super insertObject:[self removeObjectAt:count]
				     at:count + 1];
		    done = NO;
		}
		break;
	    case NO:
		if ([[self objectAt:count] doubleValue] < 
		    [[self objectAt:count + 1] doubleValue]) {    /* Swap */
		    [super insertObject:[self removeObjectAt:count]
				     at:count + 1];
		    done = NO;
		}
		break;
	    }
	}
    }

    return self;
}


// Shuts up the compiler about unused RCSId
- (const char *) rcsid
{
    return RCSId;
}


@end
